/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pe.gob.pnp.servlets;


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.sax.*;
import org.apache.fop.apps.*;
import org.w3c.dom.*;
import org.w3c.tidy.*;

/**
 *
 * @author Javero
 */
public class VistaPreviaServlet extends HttpServlet {
   private static final long serialVersionUID = 1L;
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        HttpSession session = request.getSession();
        String html = (String) session.getAttribute("htmlVistaPrevia");
        response.setContentType("application/pdf");
        OutputStream out = response.getOutputStream();
        try {
            ByteArrayInputStream htmlStream = new ByteArrayInputStream(html.getBytes());
            Document documentoOrdenado = tidy(htmlStream);
            String xsl = getServletContext().getRealPath("/WEB-INF/xml/xhtml2fo_1.xsl");
            Document fo = xml2FO(documentoOrdenado, xsl);
            fo2PDF(fo, out);
        } finally { 
            out.close();
        }
    }

    public static  Document tidy(InputStream in) {
        Document documento = null;
        Tidy tidy = new Tidy();
        tidy.setForceOutput(true);
        documento = tidy.parseDOM(in, null);
        return documento;
    }

    public static Document xml2FO(Document xml, String xsl) {
        DOMSource xmlFuente = new DOMSource(xml);
        DOMResult resultado = new DOMResult();
        Transformer transformador = getTransformer(xsl);
        if (transformador != null) {
            try {
                transformador.transform(xmlFuente, resultado);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return (Document) resultado.getNode();
    }

    public static Transformer getTransformer(String styleSheet) {

	try {

	    TransformerFactory tFactory = TransformerFactory.newInstance();

	    DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();

	    dFactory.setNamespaceAware(true);

	    DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
	    Document xslDoc = dBuilder.parse(styleSheet);
	    DOMSource xslDomSource = new DOMSource(xslDoc);

	    return tFactory.newTransformer(xslDomSource);

	}
	catch (javax.xml.transform.TransformerException e) {
	    e.printStackTrace();
	    return null;
	}
	catch (java.io.IOException e) {
	    e.printStackTrace();
	    return null;
	}
	catch (javax.xml.parsers.ParserConfigurationException e) {
	    e.printStackTrace();
	    return null;
	}
	catch (org.xml.sax.SAXException e) {
	    e.printStackTrace();
	    return null;
	}
    }


    public static void fo2PDF(Document fo, OutputStream out) {
        try {
            FopFactory fopFactory = FopFactory.newInstance();
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
            Transformer t = tFactory.newTransformer();
            Source src = new DOMSource(fo);
            Result res = new SAXResult(fop.getDefaultHandler());
            t.transform(src, res);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
